// pages/my/order/orderDetails/orderDetails.js
import Config from "../../common/config.js";
var sessionId = wx.getStorageSync('sessionId');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    orderList: {},
    userinfo: {},
    money: "",
    ordernum: "",
    open: false,
    num: "",
    youhuiArr: [],
    dikou: "",
    payOrderId: "",
    couponId: "",
    netprice: "",
    id: "",
    bookId: "",
    pageSize: "",
    amount: "",
    timeStamp: "",
    nonceStr: "",
    paySign: "",
    package: "",
    status: "",
    biaoshi: "",
    curIdx: null,
    selSta: "1",
    payid: "",
    buy: ""
  },
  chooseImg: function (e) {
    console.log(e.currentTarget.dataset.current)
    this.setData({
      curIdx: e.currentTarget.dataset.current
    })
  },
  choose: function () {
    console.log("9999")
    if (this.data.curIdx == 0) {
      this.setData({
        curIdx: null
      })
    }
  },
  selAdree: function (e) {
    console.log(e.currentTarget.dataset.pay)
    this.setData({
      payid: e.currentTarget.dataset.pay
    })
    var that = this
    if (that.data.selSta == 1) {
      that.setData({
        selSta: 2
      })
    } else if (that.data.selSta == 2) {
      that.setData({
        selSta: 1
      })
    }
  },

  showitem: function () {
    this.setData({
      open: !this.data.open
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  selAddree: function (e) {
    var sessionId = wx.getStorageSync('sessionId')
    var that = this
    var valindex = e.currentTarget.dataset.index
    var valId = e.currentTarget.id
    console.log(valId)
    this.setData({
      indexAdree: valindex,
    })
  },
  onLoad: function (options) {
    console.log(options);
    this.setData({
      buy: options.buy
    })
    if (options.orderNum) {
      this.setData({
        biaoshi: options.orderNum
      })
    }
    this.setData({
      status: options.status
    })
    var that = this

    //如果type=1表示从订单列表点入 其他表示从做书点入
    if (options.type) {

      console.log("else====");
      this.setData({
        id: options.id,
        amount: options.amount
      });

    } else {
      console.log("1====");

      this.setData({

        bookId: options.bookId,
        amount: options.number
      });
    }


    wx.setStorage({
      key: 'orderId',
      data: that.data.id,
    })
    // var sessionId = wx.getStorageSync('sessionId')
    wx.request({
      url: Config.url + '/api/pay/downOrder',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'accessToken': wx.getStorageSync('sessionId')
      },
      data: {
        id: options.id || '', //订单id，书id，书的页数
        bookId: options.bookId || '',
        amount: options.number || '',
        consigneeId: options.addid || ''
      },
      success(res) {
        if (res.data.code == 600) {
          wx.login({
            success: function (res) {
              //发送请求
              wx.request({
                url: 'https://zhangyushu.liangziqishi.shop/api/app/login', //接口地址
                data: {
                  code: res.code
                },
                method: 'POST',
                header: {
                  'content-type': 'application/json', //默认值
                  'accessToken': wx.getStorageSync('sessionId')
                },
                success: function (res) {
                  console.log(res.data)
                  wx.setStorageSync("session_key", res.data.data.data.session_key);
                  wx.setStorageSync("openid", res.data.data.data.openid)
                  wx.setStorage({
                    key: 'sessionId',
                    data: res.data.data.data.sessionId,
                  })

                  wx.request({
                    url: Config.url + '/api/pay/downOrder',
                    method: 'POST',
                    header: {
                      'content-type': 'application/json',
                      'accessToken': wx.getStorageSync('sessionId')
                    },
                    data: {
                      id: options.id || '', //订单id，书id，书的页数
                      bookId: options.bookId || '',
                      amount: options.number || '',
                      consigneeId: options.addid || ''
                    },
                    success(res) {
                      console.log(res.data.data.order.orderId)
                      that.setData({
                        orderList: res.data.data.order,
                        userinfo: res.data.data.order.consigneeInfo,
                        money: res.data.data.order.netPrice,
                        payOrderId: res.data.data.order.orderId
                      })
                      console.log(that.data.orderList);
                    }
                  })
                }
              });
            }
          });
        } else {
          console.log(res.data.data.order);
          that.setData({
            orderList: res.data.data.order,
            userinfo: res.data.data.order.consigneeInfo,
            money: res.data.data.order.netPrice,
            payOrderId: res.data.data.order.orderId
          })
        }
        console.log(that.data.orderList);
      }
    }),
      //设置id缓存传递到地址列表
      wx.setStorage({
        key: 'id',
        data: that.data.id
      })
    // 可用优惠券数量
    wx.request({
      url: Config.url + '/api/userCoupon/get_coupon_able_count',
      method: "POST",
      header: {
        'content-type': 'application/json',
        'accessToken': wx.getStorageSync('sessionId')
      },
      success: function (res) {
        console.log(res.data.data);
        that.setData({
          num: res.data.data.userCouponCount
        })
      }
    })
    //调取可用优惠券接口
    wx.request({
      url: Config.url + '/api/userCoupon/getUserCouponList',
      method: "POST",
      header: {
        'content-type': 'application/json',
        'accessToken': wx.getStorageSync('sessionId')
      },
      data: {
        status: "1"
      }, //1可用

      success: function (res) {
        console.log(res.data.data.data);
        that.setData({
          youhuiArr: res.data.data.data
        })
      }
    })

  },
  msg: function (e) {
    var obj = this;
    console.log(e._relatedInfo.anchorTargetText);
    let youhuiquanid = e._relatedInfo.anchorTargetText;
    youhuiquanid = youhuiquanid.substring(" ", 1);
    console.log(youhuiquanid)
    this.setData({
      open: !this.data.open,
      dikou: e._relatedInfo.anchorTargetText,
      couponId: youhuiquanid
    })
    // 调取实际付款接口
    wx.request({
      url: Config.url + '/api/pay/get_net_price',
      method: "POST",
      header: {
        'content-type': 'application/json',
        'accessToken': wx.getStorageSync('sessionId')
      },
      data: {
        payOrderId: obj.data.payOrderId || '', //订单号
        couponId: obj.data.couponId, //优惠券编号
        money: obj.data.money, //原价
      },
      success: function (res) {
        console.log(res.data.data.netMoney);
        obj.setData({
          money: res.data.data.netMoney
        })
      }

    })
  },
  // 支付 1余额支付，2微信支付
  gopaymoney: function () {
    var obj = this;
    if (obj.data.payid == 1) {
      wx.request({
        url: Config.url + '/api/pay/pre_pay_by_wallet',
        method: "POST",
        header: {
          'content-type': 'application/json',
          'accessToken': wx.getStorageSync('sessionId')
        },
        data: {
          netMoney: obj.data.money,
          payOrderId: obj.data.payOrderId
        },
        success: function (res) {
          if (res.data.code == 205) {
            wx.showModal({
              title: '提示',
              content: '您的钱包余额不足',
            })
            return
          }
          console.log(res);
          wx.navigateTo({
            url: '../payresult/payresult',
          })
        }
      })
    } else {
      wx.request({
        url: Config.url + '/api/pay/pre_pay_order',
        method: "POST",
        header: {
          'content-type': 'application/json',
          'accessToken': wx.getStorageSync('sessionId')
        },
        data: {
          netMoney: obj.data.money,
          payOrderId: obj.data.payOrderId
        },
        success: function (res) {
          console.log(res.data.data.mapResult);
          obj.setData({
            timeStamp: res.data.data.mapResult.timeStamp,
            paySign: res.data.data.mapResult.paySign,
            package: res.data.data.mapResult.package,
            nonceStr: res.data.data.mapResult.nonceStr,
          }),
            wx.requestPayment({
              'timeStamp': obj.data.timeStamp,
              'nonceStr': obj.data.nonceStr,
              'package': obj.data.package,
              'signType': 'MD5',
              'paySign': obj.data.paySign,
              'success': function (res) {
                console.log(res);
                //跳转到支付结果
                wx.navigateTo({
                  url: '../payresult/payresult',
                })
              },
            });

        }
      })
    }

  },
  // 跳转到优惠券
  toyouhuiquan: function () {
    wx.navigateTo({
      url: '../choose_coupon/choose_coupon',
    })
  },
  // 跳转到收货列表
  toaddress: function (e) {
    console.log(e.currentTarget.dataset.id)
    wx.navigateTo({
      url: '../adressList/adressList?dingdanid=' + e.currentTarget.dataset.id,
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    // if (this.data.curIdx==0){
    //   this.setData({
    //     curIdx:null
    //   })
    // }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})